package org.jash.ting13.book

import androidx.paging.PagingSource
import androidx.paging.PagingState
import org.jash.ting13.entity.Chapter
import org.jash.ting13.entity.SearchEntity
import org.jash.ting13.net.APIService

class ChapterPagingSource(val service:APIService, val url:String): PagingSource<Int, Chapter>() {
    override fun getRefreshKey(state: PagingState<Int, Chapter>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Chapter> {
        try {
            // Start refresh at page 1 if undefined.
            val nextPageNumber = params.key ?: 1
            val response = service.getDetail(url, nextPageNumber)
            return LoadResult.Page(
                data = response.playList,
                prevKey = null, // Only paging forward.
                nextKey = if (nextPageNumber < (response.totalPage ?: 0)) nextPageNumber + 1 else null
            )
        } catch (e: Exception) {
            return LoadResult.Error(e)
        }
    }
}